package top.kaoshanji.ch01.streams;

import com.google.common.io.Resources;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * 代码清单 ch01-07：数值流示例(1.13节)
 * author kaoshanji
 * ^_^
 * create time 2024/12/6 9:36
 */
public class PrimitiveTypeStreams {

    private static final Logger logger = LogManager.getLogger(PrimitiveTypeStreams.class);

    static final String FILE_NAME = "gutenberg/alice30.txt";

    public static void main(String[] args) throws IOException {
        logger.info("...代码清单 ch01-07：数值流示例(1.13节)...");

        // 【例1】 创建数值流 of generate range rangeClosed
        IntStream is = IntStream.of(1, 2, 3, 4, 5, 6);
        show("is", is);
        IntStream is1 = IntStream.generate(() -> (int) (Math.random() * 100));
        show("is1", is1);
        IntStream is2 = IntStream.range(5, 10);
        show("is2", is2);
        IntStream is3 = IntStream.rangeClosed(5, 10);
        show("is3", is3);

        // 【例2】 对象流 --> 基本类型流 mapToInt、mapToObj
        String fileContent = Resources.toString(Resources.getResource(FILE_NAME), StandardCharsets.UTF_8);
        Stream<String> words = Stream.of(fileContent.split("\\PL+"));
        IntStream is4 = words.mapToInt(String::length);
        show("is4", is4);
        var sentence = "\uD835\uDD46 is the set of octonions.";
        System.out.println(sentence);
        IntStream codes = sentence.codePoints();
        System.out.println(codes.mapToObj(c -> String.format("%X ", c)).collect(Collectors.joining()));

        // 【例3】 基本类型流 --> 对象流 boxed
        Stream<Integer> integers = IntStream.range(0, 100).boxed();
        IntStream is5 = integers.mapToInt(Integer::intValue);
        show("is5", is5);

    }

    public static void show(String title, IntStream stream) {

        final int SIZE = 10;
        int[] firstElements = stream.limit(SIZE + 1).toArray();
        System.out.print(title + ": ");

        for (int i = 0; i < firstElements.length; i++) {
            if (i > 0) {
                System.out.print(", ");
            }
            if (i < SIZE) {
                System.out.print(firstElements[i]);
            } else {
                System.out.print("...");
            }
        }

        System.out.println();
    }

}
